package me.stephenj.contactsweb.controller;

import com.google.common.collect.Lists;
import me.stephenj.contactsweb.model.TestQueryVO;
import me.stephenj.contactsweb.model.TestVO;
import me.stephenj.contactsweb.model.TestVOJson;
import me.stephenj.contactsweb.service.ContactsService;
import me.stephenj.contactsweb.utils.CommonResult;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;

import java.util.List;

import static com.google.common.base.Preconditions.*;

@RestController
@CrossOrigin
@RequestMapping("/api/test")
public class ContactsController {

    private final static Logger logger = LoggerFactory.getLogger(ContactsController.class);

    @Autowired
    ContactsService contactsService;

    @RequestMapping("select")
    @ResponseBody
    public CommonResult<List<TestVOJson>> select(@RequestBody TestQueryVO vo) {
        checkNotNull(vo);
        List<TestVOJson> result = contactsService.getContacts(vo);
        int total = contactsService.getCount();

        return CommonResult.successReturn(result, total);
    }

    @RequestMapping("insert")
    @ResponseBody
    public CommonResult<TestVO> insert(@RequestBody TestVOJson voJson) {
        try {
            checkNotNull(voJson);
            TestVO vo = voJson.loadJson();
            contactsService.insertContacts(vo);
            return CommonResult.successReturn(vo);
        } catch (Exception e) {
            logger.error("insert error", e);
            return CommonResult.errorReturn(200, "insert error");
        }
    }

    @RequestMapping("update")
    @ResponseBody
    public CommonResult<Integer> update(@RequestParam("keys") String keys, @RequestBody TestVOJson voJson) {
        try {
            checkNotNull(keys);
            checkNotNull(voJson);
            TestVO vo = voJson.loadJson();
            int updateNumber = 1;
            contactsService.updateContacts(vo);
            return CommonResult.successReturn(updateNumber);
        } catch (Exception e) {
            logger.error("update error", e);
            return CommonResult.errorReturn(300, "update error");
        }
    }

    @RequestMapping("delete")
    @ResponseBody
    public CommonResult<Integer> delete(@RequestParam("keys") String keys) {
        try {
            checkNotNull(keys);
            String[] keyls = keys.split(",");
            int deleteNumber = 0;
            deleteNumber = contactsService.deleteContacts(keyls);
            return CommonResult.successReturn(deleteNumber);
        } catch (Exception e) {
            logger.error("delete error", e);
            return CommonResult.errorReturn(400, "delete error");
        }
    }
}
